package hu.issue.web;

import hu.issue.ejb.UserService;
import hu.issue.entity.User;
import hu.issue.framework.web.Constants;
import hu.issue.framework.web.controller.Inject;
import hu.issue.framework.web.controller.SimpleFormController;
import hu.issue.framework.web.validation.ErrorMessages;
import hu.issue.framework.web.validation.NotEmptyValidator;
import hu.issue.framework.web.validation.RequestValidation;
import hu.issue.framework.web.validation.RequiredValidator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginController extends SimpleFormController {
	@Inject
	private UserService service;

	@Override
	protected void buildValidation(final RequestValidation validation) {
		validation.addValidator(new RequiredValidator("username", "Felhasználónév kötelező"));
		validation.addValidator(new NotEmptyValidator("username", "Felhasználónév nem lehet üres"));

		validation.addValidator(new RequiredValidator("password", "Jelszó megadása kötelező"));
		validation.addValidator(new NotEmptyValidator("password", "Jelszó nem lehet üres"));
	}

	@Override
	protected boolean handleSubmissionInternal(final HttpServletRequest request, final HttpServletResponse response, final ErrorMessages messages) throws Exception {
		final String userName = request.getParameter("username");
		final String password = request.getParameter("password");

		final User user = this.service.findUserByUserNameAndPassword(userName, password);

		if (user == null) {
			messages.addMessage("Felhasználónév vagy a jelszó nem jó");
			return false;

		}

		request.getSession().setAttribute(Constants.USER_SESSION_NAME, user);
		return true;
	}

	@Override
	protected String getSuccessView() {
		return "redirect:dashboard.do";
	}

}
